<template>
  <div class="car-rental-home">
    <!-- 导航栏 -->
    <el-header class="header">
      <div class="logo">爱坤租车</div>
      <div class="nav-menu">
        <el-button text style="color: #000">首页</el-button>
        <el-button text style="color: #000" @click="router.push('/CarInfo')"
          >租车服务</el-button
        >
        <el-button text style="color: #000" @click="router.push('/AboutUs')"
          >关于我们</el-button
        >
      </div>
      <div class="user-section">
        <el-button v-if="!userStore.isLogin" @click="login" type="primary"
          >登录</el-button
        >
        <el-avatar
          v-else
          :src="userStore.getImgUrl || defaultAvatar"
          @click="goToProfile"
        />
      </div>
    </el-header>

    <!-- Banner轮播图 -->
    <el-main class="main-content">
      <el-carousel :interval="4000" type="card" height="300px">
        <el-carousel-item v-for="item in banners" :key="item">
          <img :src="item" class="banner-image" />
        </el-carousel-item>
      </el-carousel>

      <!-- 条件搜索车辆 -->
      <div class="search-section">
        <div class="advanced-search-content">
          <el-form
            :model="searchConditions"
            label-width="80px"
            class="search-conditions"
          >
            <el-row :gutter="20">
              <el-col :span="6">
                <el-form-item label="车牌号">
                  <el-input
                    v-model="searchConditions.plate"
                    placeholder="请输入车牌号"
                  ></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="地理位置">
                  <el-select
                    v-model="selectedProvince"
                    placeholder="请选择省份"
                    clearable
                    @change="onProvinceChange"
                    style="width: 100%"
                  >
                    <el-option
                      v-for="province in provinces"
                      :key="province.pid"
                      :label="province.pname"
                      :value="province.pid"
                    ></el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label=" ">
                  <el-select
                    v-model="selectedCity"
                    placeholder="请选择城市"
                    clearable
                    @change="onCityChange"
                    :disabled="!selectedProvince"
                    style="width: 100%"
                  >
                    <el-option
                      v-for="city in cities"
                      :key="city.cid"
                      :label="city.cname"
                      :value="city.cid"
                    ></el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label=" ">
                  <el-select
                    v-model="searchConditions.lid"
                    placeholder="请选择站点"
                    clearable
                    :disabled="!selectedCity"
                    style="width: 100%"
                  >
                    <el-option
                      v-for="location in locations"
                      :key="location.lid"
                      :label="location.lname"
                      :value="location.lid"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="价格区间">
                  <div class="price-range">
                    <el-input
                      v-model="searchConditions.minPrice"
                      placeholder="最低价"
                    ></el-input>
                    <span class="separator">-</span>
                    <el-input
                      v-model="searchConditions.maxPrice"
                      placeholder="最高价"
                    ></el-input>
                  </div>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="车辆类型">
                  <el-select
                    v-model="searchConditions.ctypeid"
                    placeholder="请选择车辆类型"
                    clearable
                    style="width: 100%"
                  >
                    <el-option
                      v-for="item in carTypes"
                      :key="item.ctypeid"
                      :label="item.ctypename"
                      :value="item.ctypeid"
                    ></el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="车辆品牌">
                  <el-select
                    v-model="searchConditions.brandid"
                    placeholder="请选择车辆品牌"
                    clearable
                    style="width: 100%"
                  >
                    <el-option
                      v-for="item in carBrands"
                      :key="item.brandid"
                      :label="item.brandname"
                      :value="item.brandid"
                    ></el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label=" ">
                  <div class="search-actions">
                    <el-button type="primary" @click="fetchCars"
                      >搜索</el-button
                    >
                    <el-button @click="resetSearch">重置</el-button>
                  </div>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </div>
      </div>

      <!-- 车辆信息展示区 -->
      <div class="car-cards">
        <el-card
          v-for="car in cars"
          :key="car.carid"
          class="car-card"
          shadow="hover"
        >
          <img :src="car.pictures" class="car-image" />
          <div class="car-info">
            <h3>{{ car.carname }}</h3>
            <p>品牌: {{ car.brandname }}</p>
            <p>类型: {{ car.ctypename }}</p>
            <p>价格: ¥{{ car.price }}/天</p>
            <el-button type="primary" size="small" @click="viewCarDetail(car)"
              >查看详情</el-button
            >
          </div>
        </el-card>
      </div>

      <!-- 加载状态提示 -->
      <div class="loading-container" v-if="loading">
        <el-skeleton v-for="i in 3" :key="i" :loading="loading" animated>
          <template #template>
            <el-skeleton-item
              variant="image"
              style="width: 100%; height: 200px"
            />
            <div style="padding: 14px">
              <el-skeleton-item variant="h3" style="width: 50%" />
              <div>
                <el-skeleton-item variant="text" style="margin-right: 16px" />
                <el-skeleton-item variant="text" style="width: 30%" />
              </div>
            </div>
          </template>
        </el-skeleton>
      </div>

      <!-- 没有更多数据提示 -->
      <div class="no-more-data" v-if="noMoreData">
        <el-divider>
          <el-text size="small" type="info">没有更多车辆了</el-text>
        </el-divider>
      </div>
    </el-main>
  </div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount, computed } from "vue";
import api from "@/util/service";
import { useRouter } from "vue-router";
import { ElMessage } from "element-plus";
import { useLoginStore } from "@/stores/userStores";

const router = useRouter();
const userStore = useLoginStore();

// 默认头像
const defaultAvatar =
  "https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png";

// 轮播图图片地址
const banners = ref([
  "https://esan688.oss-cn-beijing.aliyuncs.com/car/car/%E6%96%B0%E5%BB%BA%E6%96%87%E4%BB%B6%E5%A4%B9/%E5%88%B6%E4%BD%9C%E7%A7%9F%E8%BD%A6%E7%B3%BB%E7%BB%9F%20banner%20%E5%9B%BE%20%281%29.png",
  "https://esan688.oss-cn-beijing.aliyuncs.com/car/car/%E6%96%B0%E5%BB%BA%E6%96%87%E4%BB%B6%E5%A4%B9/%E5%88%B6%E4%BD%9C%E7%A7%9F%E8%BD%A6%E7%B3%BB%E7%BB%9F%20banner%20%E5%9B%BE%20%282%29.png",
  "https://esan688.oss-cn-beijing.aliyuncs.com/car/car/%E6%96%B0%E5%BB%BA%E6%96%87%E4%BB%B6%E5%A4%B9/%E5%88%B6%E4%BD%9C%E7%A7%9F%E8%BD%A6%E7%B3%BB%E7%BB%9F%20banner%20%E5%9B%BE.png",
]);

// 车辆数据
const cars = ref([]);

// 分页相关状态
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);
const loading = ref(false);
const noMoreData = ref(false);

// 搜索条件
const searchConditions = ref({
  plate: "",
  lid: "",
  minPrice: "",
  maxPrice: "",
  ctypeid: "",
  brandid: "",
});

// 车辆类型和品牌选项
const carTypes = ref([]);
const carBrands = ref([]);

// 地理位置相关数据
const provinces = ref([]);
const cities = ref([]);
const locations = ref([]);

// 选中的地理位置
const selectedProvince = ref("");
const selectedCity = ref("");

// 省份变化时的处理
const onProvinceChange = (provinceId) => {
  selectedCity.value = "";
  searchConditions.value.lid = "";
  cities.value = [];
  locations.value = [];

  if (provinceId) {
    fetchCities(provinceId);
  }
};

// 城市变化时的处理
const onCityChange = (cityId) => {
  searchConditions.value.lid = "";
  locations.value = [];

  if (cityId) {
    fetchLocations(cityId);
  }
};

// 获取省份数据
const fetchProvinces = async () => {
  try {
    const response = await api.get("/position/getAllProvince");
    if (response.code === 200) {
      provinces.value = response.data;
    }
  } catch (error) {
    console.error("获取省份数据失败:", error);
    ElMessage.error("获取省份数据失败");
  }
};

// 根据省份ID获取城市数据
const fetchCities = async (pid) => {
  try {
    const response = await api.get(`/position/getCityByPid/${pid}`);
    if (response.code === 200) {
      cities.value = response.data;
    }
  } catch (error) {
    console.error("获取城市数据失败:", error);
    ElMessage.error("获取城市数据失败");
  }
};

// 根据城市ID获取站点数据
const fetchLocations = async (cid) => {
  try {
    const response = await api.get(`/position/getLocationByCid/${cid}`);
    if (response.code === 200) {
      locations.value = response.data;
    }
  } catch (error) {
    console.error("获取站点数据失败:", error);
    ElMessage.error("获取站点数据失败");
  }
};

// 获取车辆类型和品牌列表
const fetchCarTypesAndBrands = async () => {
  try {
    const typesResponse = await api.get("/carTpye/selectCarTpye");
    const brandsResponse = await api.get("/carTpye/selectCarBrand");

    if (typesResponse.code === 200) {
      carTypes.value = typesResponse.data;
    }

    if (brandsResponse.code === 200) {
      carBrands.value = brandsResponse.data;
    }
  } catch (error) {
    console.error("获取车辆类型和品牌失败:", error);
    ElMessage.error("获取车辆类型和品牌失败");
  }
};

// 重置搜索条件
const resetSearch = () => {
  searchConditions.value = {
    plate: "",
    lid: "",
    minPrice: "",
    maxPrice: "",
    ctypeid: "",
    brandid: "",
  };
  selectedProvince.value = "";
  selectedCity.value = "";
  cities.value = [];
  locations.value = [];
  fetchCars();
};

// 获取车辆数据（更新 fetchCars 方法）
const fetchCars = async () => {
  if (loading.value || noMoreData.value) return;

  loading.value = true;
  try {
    const response = await api.post("/tcar/selectCars", {
      pageNum: 1,
      pageSize: pageSize.value,
      ...searchConditions.value, // 添加搜索条件
    });

    if (response.code === 200) {
      const newCars = response.data.records;
      total.value = response.data.total;

      if (currentPage.value === 1) {
        cars.value = newCars;
      } else {
        cars.value = [...cars.value, ...newCars];
      }

      if (cars.value.length >= total.value) {
        noMoreData.value = true;
      }
    }
  } catch (error) {
    console.error("获取车辆数据失败:", error);
    ElMessage.error("获取车辆数据失败");
  } finally {
    loading.value = false;
  }
};

// 登录方法
const login = () => {
  router.push("/login");
};

// 跳转到个人中心
const goToProfile = () => {
  router.push("/main");
};

// 查看车辆详情
const viewCarDetail = (car) => {
  sessionStorage.setItem("carId", car.carid);
  router.push("/CarDetails");
};

// 滚动事件处理
const handleScroll = () => {
  // 获取页面滚动信息
  const scrollTop =
    document.documentElement.scrollTop || document.body.scrollTop;
  const clientHeight = document.documentElement.clientHeight;
  const scrollHeight = document.documentElement.scrollHeight;

  // 判断是否滚动到底部（距离底部50px时开始加载）
  if (scrollTop + clientHeight >= scrollHeight - 50) {
    // 如果还有更多数据且未在加载中，则加载下一页
    if (!noMoreData.value && !loading.value) {
      currentPage.value++;
      fetchCars();
    }
  }
};

// 页面加载时获取数据和车辆类型、品牌列表
onMounted(() => {
  fetchCars();
  fetchCarTypesAndBrands(); // 获取车辆类型和品牌列表
  fetchProvinces(); // 获取省份数据
  window.addEventListener("scroll", handleScroll);
});
// 组件卸载前移除滚动事件监听
onBeforeUnmount(() => {
  window.removeEventListener("scroll", handleScroll);
});
</script>

<style scoped>
.car-rental-home {
  min-height: 100vh;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  background-color: #545c64;
  color: rgb(255, 255, 255);
  padding: 0 20px;
  position: sticky;
  top: 0;
  z-index: 100;
}

.logo {
  font-size: 24px;
  font-weight: bold;
}

.nav-menu {
  display: flex;
  gap: 20px;
}

.user-section {
  cursor: pointer;
}

.main-content {
  margin: 0 auto;
  width: 80%;
  padding: 20px;
}

.banner-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.search-section {
  margin: 20px 0;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 12px;
  padding: 25px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
}

.advanced-search-content {
  background-color: rgba(255, 255, 255, 0.95);
  border-radius: 10px;
  padding: 20px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
}

.search-conditions :deep(.el-form-item__label) {
  color: #333;
  font-weight: 500;
}

.price-range {
  display: flex;
  align-items: center;
  gap: 10px;
}

.price-range .separator {
  color: #666;
  font-weight: bold;
}

.search-actions {
  display: flex;
  gap: 15px;
}

.search-actions .el-button {
  border-radius: 6px;
}

.car-cards {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 20px;
  margin-top: 30px;
}

.car-card {
  display: flex;
  flex-direction: column;
  border-radius: 12px;
  overflow: hidden;
  transition: transform 0.3s, box-shadow 0.3s;
}

.car-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 10px 20px rgba(0, 0, 0, 0.15);
}

.car-image {
  width: 100%;
  height: 200px;
  object-fit: cover;
}

.car-info {
  padding: 15px;
  flex-grow: 1;
  background-color: #fff;
}

.car-info h3 {
  margin: 0 0 10px 0;
  color: #333;
}

.car-info p {
  margin: 5px 0;
  color: #666;
}

.loading-container {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 20px;
  margin-top: 30px;
}

.no-more-data {
  text-align: center;
  margin: 30px 0;
}

.el-button > span {
  color: #fff;
  align-items: center;
  display: inline-flex;
}

@media (max-width: 768px) {
  .el-col {
    width: 100%;
    margin-bottom: 15px;
  }

  .search-section {
    padding: 15px;
  }

  .advanced-search-content {
    padding: 15px;
  }
}
</style>
